package com.nzf.vote.service.impl;

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.nzf.vote.entity.UserVote;
import com.nzf.vote.entity.Vote;
import com.nzf.vote.mapper.UserMapper;
import com.nzf.vote.mapper.UserVoteMapper;
import com.nzf.vote.mapper.VoteMapper;
import com.nzf.vote.model.dto.UserVoteDto;
import com.nzf.vote.service.IUserVoteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author nzf
 * @since 2022-07-25
 */
@Service
public class UserVoteServiceImpl extends ServiceImpl<UserVoteMapper, UserVote> implements IUserVoteService {
    @Autowired
    UserVoteMapper userVoteMapper;
    @Autowired
    VoteMapper voteMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public List<UserVoteDto> getUserList() {
        List<UserVoteDto> userVoteDtos = new ArrayList<>();
        userVoteMapper.selectList(null).forEach(userVote -> {
            UserVoteDto userVoteDto = new UserVoteDto();
            userVoteDto.setTheme(voteMapper.selectById(userVote.getVoteId()).getTheme());
            userVoteDto.setId(userVote.getId());
            userVoteDto.setOption(userVote.getMyOption());
            userVoteDto.setCreateTime(userVote.getCreateTime());
            userVoteDto.setUserId(userVote.getUserId());
            userVoteDto.setVoteId(userVote.getVoteId());
            userVoteDtos.add(userVoteDto);
        });
        return userVoteDtos;
    }

    @Override
    public List<UserVoteDto> getUserVoteByUserId(Integer userId) {
        List<UserVoteDto> userVoteDtos = new ArrayList<>();
        userVoteMapper.getUserVoteByUserId(userId).forEach(userVote -> {
            UserVoteDto userVoteDto = new UserVoteDto();
            userVoteDto.setTheme(voteMapper.selectById(userVote.getVoteId()).getTheme());
            userVoteDto.setId(userVote.getId());
            userVoteDto.setOption(userVote.getMyOption());
            userVoteDto.setCreateTime(userVote.getCreateTime());
            userVoteDto.setUserId(userVote.getUserId());
            userVoteDto.setVoteId(userVote.getVoteId());
            userVoteDtos.add(userVoteDto);
        });
        return userVoteDtos;
    }



    @Override
    public Integer insertUserVote(UserVote userVote) {
        LocalDateTime dateTime = LocalDateTime.now();
        userVote.setCreateTime(dateTime);
        int insert = userVoteMapper.insert(userVote);
        try {
            Vote vote = voteMapper.selectById(userVote.getVoteId());
            vote.setNum(vote.getNum()+1);
            voteMapper.updateById(vote);
        }catch (Exception e){
            return insert;
        }
        return insert;
    }

}
